import urllib2
import base64
from api_base import ApiBase

class Twitter(ApiBase):
    '''
    register urls 
    '''
    def __init__(self):
        self.debug = True
        self.user_agent_header = "Twitrazzi"
        
        self.urls = {
            'account_verify_credentials': 'http://twitter.com/account/verify_credentials.xml',
            'account_end_session':'http://twitter.com/account/end_session.xml',
            'statuses_update':'http://twitter.com/statuses/update.xml',
            'statuses_public_timeline':'http://twitter.com/statuses/public_timeline.xml',
            'statuses_friends_timeline':'http://twitter.com/statuses/friends_timeline.xml',
            'statuses_user_timeline':'http://twitter.com/statuses/%s.xml',
            'search':'http://search.twitter.com/search.atom?q='
        }

    '''
    verify a users account credentials
    returns extended user information object 
    http://apiwiki.twitter.com/REST+API+Documentation#Extendeduserinformationelement
    '''
    def account_verify_credentials(self,username,password):
        req = urllib2.Request(self.urls['account_verify_credentials'])
        base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
        authheader =  "Basic %s" % base64string
        req.add_header("Authorization", authheader)
        return self.handle_response(self.send_request(req))
    
    '''
    Ends the session of the authenticating user, returning a null cookie.
    '''
    def account_end_session(self):
        return self.handle_response(self.submit_post(self.urls['account_end_session'],{'account':'end_session'}))
    
    '''
    Returns the 20 most recent statuses from non-protected users who have set a custom user icon
    '''
    def statuses_public_timeline(self):
        return self.handle_response(self.submit_get(self.urls['statuses_public_timeline']))
    
    '''
    Returns the 20 most recent statuses posted by the authenticating user and that user's friends
    '''
    def statuses_friends_timeline(self,since_id=False,max_id=False,count=False,page=False):
        return self.handle_response(self.submit_get(self.urls['statuses_friends_timeline']))
    
    '''
    Returns the 20 most recent statuses posted from the authenticating user. 
    It's also possible to request another user's timeline via the id parameter below. 
    '''
    def statuses_user_timeline(self,id=False,user_id=False,screen_name=False,since_id=False,max_id=False,page=False):
        return self.handle_response(self.submit_get(self.urls['statuses_user_timeline'])) 
    
    '''
    update status for authenticated user
    '''
    def statuses_update(self,status,in_reply_to_status_id):
        values = {
            'status' : status,
            'in_reply_to_status_id':in_reply_to_status_id
        }
        return self.handle_response(self.submit_post(self.urls['statuses_update'],data))
    
    '''
    search twitter
    required:
    query
    options:
    lang: restricts tweets to the given language, given by an ISO 639-1 code. Ex: http://search.twitter.com/search.atom?lang=en&q=devo
    rpp: the number of tweets to return per page, up to a max of 100. Ex: http://search.twitter.com/search.atom?lang=en&q=devo&rpp=15
    page: the page number (starting at 1) to return, up to a max of roughly 1500 results (based on rpp * page)
    since_id: returns tweets with status ids greater than the given id.
    geocode: returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile. The parameter value is specified by "latitide,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers). Ex: http://search.twitter.com/search.atom?geocode=40.757929%2C-73.985506%2C25km. Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this geocode parameter to search near geocodes directly.
    show_user: when "true", adds "<user>:" to the beginning of the tweet. This is useful for readers that do not display Atom's author field. The default is "false".
    '''
    def search(self,query,options={}):
        req_url = "%s%s" % (self.urls['search'],query)
        if len(options) > 0:
             req_url = "%s&%s" % (req_url,self.build_query(options))
        return self.handle_response(self.submit_get(req_url)) 
    
    '''
    following functions are helper functions to make searching easier
    they format your search query and feed it to the main search function
    all options are the same as the main search function
    '''
    
    '''
    Find tweets from a user
    '''
    def search_from_user(self,username,options={}):
        query = "from%%3A%s" % username
        
        return self.search(query,options)
    
    '''
    Find tweets to a user
    '''
    def search_to_user(self,username,options={}):
        query = "to%%3A%s" % username
        return self.search(query,options)
    
    '''
    Find tweets referencing a user
    '''
    def search_referencing_user(self,username,options={}):
        query = "%%40%s" % username
        return self.search(query,options)
    
    '''
    Find tweets containing a hashtag (up to 16 characters)
    '''
    def search_containing_hashtag(self,hashtag,options={}):
        query = "%%23%s" % hashtag
        return self.search(query,options)
    